<template>
  <el-config-provider :locale="zhCn">
    <router-view v-slot="{ Component }">
      <transition name="fade" mode="out-in">
        <component :is="Component" />
      </transition>
    </router-view>
  </el-config-provider>
</template>

<script setup>
import { onBeforeMount, onErrorCaptured } from 'vue'
import { ElConfigProvider } from 'element-plus'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const store = useStore()
const router = useRouter()

onBeforeMount(() => {
  store.commit('user/CLEAR_USER')
  if (router.currentRoute.value.meta.requiresAuth) {
    router.push('/login')
  }
})

onBeforeMount(async () => {
  const theme = localStorage.getItem('theme') || 'light'
  store.commit('user/SET_THEME', theme)
  document.documentElement.setAttribute('data-theme', theme)
})

onBeforeMount(async () => {
  const token = localStorage.getItem('token')
  if (token) {
    try {
      await store.dispatch('user/getUserInfo')
      try {
        await store.dispatch('dashboard/getDashboardData')
      } catch (error) {
        console.error('获取仪表盘数据失败:', error)
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      store.commit('user/CLEAR_USER')
    }
  }
})

onErrorCaptured((error) => {
  console.error('Captured error:', error)
  if (error?.response?.status !== 404 && error?.code !== 'ERR_CANCELED') {
    ElMessage.error('操作失败，请稍后重试')
  }
  return false
})
</script>

<style>
html, body {
  margin: 0;
  padding: 0;
  height: 100%;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

#app {
  height: 100%;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

:root {
  --el-color-primary: #409EFF;
  --el-color-success: #67C23A;
  --el-color-warning: #E6A23C;
  --el-color-danger: #F56C6C;
  --el-color-info: #909399;
}

[data-theme='dark'] {
  --el-bg-color: #1e1e1e;
  --el-bg-color-page: #141414;
  --el-text-color-primary: #E5EAF3;
  --el-text-color-regular: #CFD3DC;
  --el-text-color-secondary: #A3A6AD;
  --el-border-color-light: #363637;
  --el-fill-color-light: #262727;
}

[data-theme='light'] {
  --el-bg-color: #ffffff;
  --el-bg-color-page: #f2f3f5;
  --el-text-color-primary: #303133;
  --el-text-color-regular: #606266;
  --el-text-color-secondary: #909399;
  --el-border-color-light: #dcdfe6;
  --el-fill-color-light: #f5f7fa;
}
</style>
